<template>
  <div class="main">
    <div class="nav-bar">
      <div
        class="nav-item"
        @click="switchTab(1)"
      ><span
        class='item-word'
        :class="{'active':activeTab == 1}"
      >蓝牙打印机</span></div>
      <!-- <div
        class="nav-item"
        @click="switchTab(2)"
      ><span
        class='item-word'
        :class="{'active':activeTab == 2}"
      >云打印机</span></div> -->
    </div>
    <div v-if="activeTab == 1">
      <div class="item-list">
        <div
          class="item"
          v-for="(lanyaPrint,index) in lanyaPrintList"
        ><span>{{ lanyaPrint.localName }}</span><a @click="doAdd(lanyaPrint)">添加</a></div>
      </div>
      <div class="item-list yitianjia">
        <div v-for="(print,index) in printList">
          <div class="item">
            <div><span>{{ print.aliasName }}</span><span class="yitianjia">已添加</span></div>
          </div>
          <div class="item">
            <a
              style="float: left"
              @click="doTest(print)"
            >测试打印</a><a @click="doDel(print)">删除</a><a @click="doEdit(print)">编辑名称</a>
          </div>
        </div>
      </div>
      <!-- 没有更多数据 -->
      <div class="no-data">亲，没有更多了～</div>
      <div style="margin-left: 8px">
        <p style="margin-bottom: 10px">温馨提示：</p>
        <p>1、搜索蓝牙打印机前，请打开蓝牙打印机，打开手机蓝牙功能， 部分安卓手机需要打开定位功能。</p>
        <p>2、以上操作已执行，还无法找到打印,请重启打印机再次搜索。</p>
        <p>3、如有问题，请联系客服QQ:800157966。</p>
      </div>
      <div
        class="foot"
        @click="search"
      >{{ btnTitle }}
      </div>
    </div>

    <cloudPrint v-if="activeTab==2">
    </cloudPrint>

    <toast ref="toast"/>
    <tanchuan
      ref="tanchuanDel"
      :title="title"
      :content="content"
      @doCancle="doCancleDel"
      @doConfirm="doConfirmDel"
    ></tanchuan>
    <bianjidayinji :currentPrint="currentPrint" v-if="showEdit" @doWarn="doWarn" @doCancle="doCancleEdit" @doConfirm="doConfirmEdit"></bianjidayinji>
  </div>
</template>

<script>
    import api from "@/utils/api";
    import toast from "@/components/toast";
    import cloudPrint from "./cloudPrint";
    import tanchuan from "@/components/tanchuan";
    import bianjidayinji from "@/components/bianjidayinji";
    import str2ab from "string-to-arraybuffer"

    export default {
        components: {toast, cloudPrint,tanchuan,bianjidayinji},

        data() {
            return {
                btnTitle: "搜索蓝牙打印机",
                _discoveryStarted: false,
                printList: [],
                lanyaPrintList: [],
                activeTab: 1,
                currentPrint : {},
                title : '确定删除',
                content : "确定删除此打印机吗",
                showEdit : false,
                _deviceId : '',
                _serviceId : '',
                _characteristicId : '',
                systemPrintList : [],
                msg : '0'
            };
        },

        onLoad() {
            this.loadDayin();
            this.loadSystem();
            this.lanyaPrintList = [
                /* {
                   deviceId: "asdasdsad",
                   deviceName: "设备"
                 },
                 {
                   deviceId: "asdasdsad",
                   deviceName: "设备"
                 }*/
            ];
            this.printList = [
                /* {
                   deviceId: "345345345",
                   deviceName: "设备"
                 },
                 {
                   deviceId: "345345345",
                   deviceName: "设备"
                 }*/
            ];
        },

        methods: {
            loadSystem(){
                var _this = this;
                wx.request({
                    url: wx.getStorageSync("otherPath") + api.systemPrinterList + "?ecstoken=" + wx.getStorageSync('sessionId'),
                    method: "POST",
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    data: {
                    },
                    success(res) {
                      console.log(res);
                        if(res.data.code != 200){
                            _this.$refs.toast.show(res.data.msg);
                            return ;
                        }
                        _this.systemPrintList = res.data.data;
                    },
                    fail() {
                        _this.$refs.toast.show('网络异常')
                    },
                })
            },

            doAdd(print) {
                this.currentPrint = print;
                var _this = this;
                wx.request({
                    url: wx.getStorageSync("otherPath") + api.addBluetoothPrinter + "?ecstoken=" + wx.getStorageSync('sessionId'),
                    method: "POST",
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    data: {
                        deviceId: print.deviceId,
                        deviceName: print.localName+"_02",
                        aliasName: print.localName+"_02",
                        type: '0',
                        systemDeviceCode : print.filterName
                    },
                    success(res) {
                        if(res.data.code != 200){
                            _this.$refs.toast.show(res.data.msg);
                            return ;
                        }
                        _this.$refs.toast.show('添加成功')
                        _this.loadDayin();
                    },
                    fail() {
                        _this.$refs.toast.show('网络异常')
                    },
                })
            },

            doCancleEdit(){
                this.showEdit = false;
            },

            doConfirmEdit(print){
                var _this = this;
                wx.request({
                    url: wx.getStorageSync("otherPath") + api.modifyUserPrinter + "?ecstoken=" + wx.getStorageSync('sessionId'),
                    method: "POST",
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    data: {
                        id: print.id,
                        deviceId: print.deviceId,
                        deviceName: print.deviceName,
                        aliasName: print.aliasName,
                        type: '0'
                    },
                    success(res) {
                        if(res.data.code != 200){
                            _this.$refs.toast.show(res.data.msg);
                            return ;
                        }
                        _this.$refs.toast.show('修改成功')
                        _this.loadDayin();
                    },
                    fail() {
                        _this.$refs.toast.show('网络异常')
                    },
                    complete(){
                        _this.showEdit = false;
                    }
                })
            },

            doEdit(print) {
                this.currentPrint = print;
                this.showEdit = true;
            },

            doCancleDel(){
                this.$refs.tanchuanDel.hidden();
            },

            doConfirmDel(){
                var _this = this;
                wx.request({
                    url: wx.getStorageSync("otherPath") + api.deleteUserPrinter + "?ecstoken=" + wx.getStorageSync('sessionId'),
                    method: "POST",
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    data: {
                        id: _this.currentPrint.id,
                    },
                    success(res) {
                        if(res.data.code != 200){
                            _this.$refs.toast.show(res.data.msg);
                            return ;
                        }
                        _this.$refs.toast.show('删除成功');
                        _this.loadDayin();
                    },
                    fail() {
                        _this.$refs.toast.show('网络异常');
                    },
                    complete(){
                        _this.$refs.tanchuanDel.hidden();
                    }
                })
            },

            doWarn(msg){
                this.$refs.toast.show(msg);
            },

            doDel(print) {
                this.currentPrint = print;
                this.$refs.tanchuanDel.show();
            },

            doTest(print) {
                var _this = this;
                wx.request({
                    url: wx.getStorageSync("otherPath") + api.printBluetoothTest + "?ecstoken=" + wx.getStorageSync("sessionId"),
                    method: "POST",
                    data: {
                        deviceName : print.deviceName
                    },
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    success(res) {
                        if(res.data.code != 200){
                            _this.$refs.toast.show(res.data.msg);
                            return ;
                        }
                        console.log(res);
                        _this.msg = res.data.data;
                        wx.openBluetoothAdapter({
                            success: res => {
                                console.log("openBluetoothAdapter success", res);
                                _this.createBLEConnection(print.deviceId);
                            },
                            fail: res => {
                                if (res.errCode === 10001) {
                                    _this.$refs.toast.show("请打开蓝牙");
                                    wx.onBluetoothAdapterStateChange(function (res) {
                                        console.log("onBluetoothAdapterStateChange", res);
                                        if (res.available) {
                                            _this.createBLEConnection(print.deviceId);
                                        }
                                    });
                                }
                            }
                        });
                    },
                    fail() {
                        _this.$refs.toast.show("网络异常");
                    }
                })

            },

            loadDayin() {
                var _this = this;
                wx.request({
                    url: wx.getStorageSync("otherPath") + api.printerList + "?ecstoken=" + wx.getStorageSync("sessionId"),
                    method: "POST",
                    header: {
                        ecstoken : wx.getStorageSync('sessionId'),
                        fslb : wx.getStorageSync('fslb')
                    },
                    data: {},
                    success(res) {
                        if(res.data.code != 200){
                            _this.$refs.toast.show(res.data.msg);
                            return ;
                        }
                        _this.printList = res.data.data;
                    },
                    fail() {
                        _this.$refs.toast.show("网络异常");
                    }
                })
            },


            search() {
                if (!this._discoveryStarted) {
                    this.btnTitle = "停止搜索";
                    this.openBluetoothAdapter();
                } else {
                    this.btnTitle = "搜索蓝牙打印机";
                    this.stopBluetoothDevicesDiscovery();
                }
            },

            //获取蓝牙设备状态
            openBluetoothAdapter() {
                var _this = this;
                this._discoveryStarted = true;
                wx.openBluetoothAdapter({
                    success: res => {
                        console.log("openBluetoothAdapter success", res);
                        _this.startBluetoothDevicesDiscovery();
                    },
                    fail: res => {
                        if (res.errCode === 10001) {
                            _this.$refs.toast.show("请打开蓝牙");
                            wx.onBluetoothAdapterStateChange(function (res) {
                                console.log("onBluetoothAdapterStateChange", res);
                                if (res.available) {
                                    _this.startBluetoothDevicesDiscovery();
                                }
                            });
                        }
                    }
                });
            },

            //发现设备
            startBluetoothDevicesDiscovery() {
                var _this = this;
                wx.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey: true,
                    success: res => {
                        console.log("startBluetoothDevicesDiscovery success", res);
                        _this.onBluetoothDeviceFound();
                    }
                });
            },

            //停止
            stopBluetoothDevicesDiscovery() {
                this._discoveryStarted = false;
                wx.stopBluetoothDevicesDiscovery();
            },

            //发下设备
            onBluetoothDeviceFound() {
                var _this = this;
                wx.onBluetoothDeviceFound(res => {
                    res.devices.forEach(device => {
                        if (!device.name || !device.localName) {
                            return
                        }
                        for(var i in _this.systemPrintList){
                            if(device.name.startsWith(_this.systemPrintList[i].filterName)){
                                var foundDevices = _this.lanyaPrintList
                                var idx = _this.inArray(foundDevices, 'deviceId', device.deviceId)
                                if (idx === -1) {
                                    device.filterName = _this.systemPrintList[i].deviceCode;
                                    _this.lanyaPrintList.push(device);
                                } else {
                                    device.filterName = _this.systemPrintList[i].deviceCode;
                                    _this.lanyaPrintList[idx] = device;
                                }
                            }
                        }
                    });
                });
            },

            //创建链接
            createBLEConnection(deviceId) {
                var _this = this;
                wx.createBLEConnection({
                    deviceId,
                    success: res => {
                        console.log(res);
                        this.getBLEDeviceServices(deviceId);
                    },
                    fail: res => {
                        _this.$refs.toast.show("未发现设备");
                    }
                });
                this.stopBluetoothDevicesDiscovery();
            },

            //关闭连接
            closeBLEConnection() {
                wx.closeBLEConnection({
                    deviceId: this.data.deviceId
                });
                this.setData({
                    connected: false,
                    chs: [],
                    canWrite: false
                });
            },

            //获取设备
            getBLEDeviceServices(deviceId) {
                var _this = this;
                wx.getBLEDeviceServices({
                    deviceId,
                    success: res => {
                        for (let i = 0; i < res.services.length; i++) {
                            if (res.services[i].isPrimary) {
                                this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
                                //return;
                            }
                        }
                    },
                    fail: res => {
                        _this.$refs.toast.show("未发现设备");
                    }
                });
            },

            getBLEDeviceCharacteristics(deviceId, serviceId) {
                var _this = this;
                wx.getBLEDeviceCharacteristics({
                    deviceId,
                    serviceId,
                    success: res => {
                        console.log(
                            "getBLEDeviceCharacteristics success",
                            res.characteristics
                        );
                        for (let i = 0; i < res.characteristics.length; i++) {
                            let item = res.characteristics[i];
                            if (item.properties.read) {
                                wx.readBLECharacteristicValue({
                                    deviceId,
                                    serviceId,
                                    characteristicId: item.uuid,
                                    success (res) {
                                        console.log('readBLECharacteristicValue:', res.errCode)
                                    }
                                });
                            }
                            if (item.properties.write) {
                                _this._deviceId = deviceId;
                                _this._serviceId = serviceId;
                                _this._characteristicId = item.uuid;
                                _this.writeBLECharacteristicValue();
                                break;
                            }
                            if (item.properties.notify || item.properties.indicate) {
                                wx.notifyBLECharacteristicValueChange({
                                    deviceId,
                                    serviceId,
                                    characteristicId: item.uuid,
                                    state: true
                                });
                            }
                        }
                    },
                    fail(res) {
                        console.error("getBLEDeviceCharacteristics", res);
                    }
                });
                // 操作之前先监听，保证第一时间获取数据
                wx.onBLECharacteristicValueChange(res => {
                    console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
                    console.log(_this.ab2hex(res.value))
                });
            },
            writeBLECharacteristicValue() {
                console.log("发送打印数据")
                // 向蓝牙设备发送16进制数据
                var buffer = this.str2abnew(this.msg);
                wx.writeBLECharacteristicValue({
                    deviceId: this._deviceId,
                    serviceId: this._serviceId,
                    characteristicId: this._characteristicId,
                    value: buffer,
                    success (res) {
                        console.log('writeBLECharacteristicValue success', res.errMsg)
                    },
                    fail(res) {
                        console.error("getBLEDeviceCharacteristics", res);
                    }
                });
            },
            closeBluetoothAdapter() {
                wx.closeBluetoothAdapter();
                this._discoveryStarted = false;
            },

            inArray(arr, key, val) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i][key] === val) {
                        return i;
                    }
                }
                return -1;
            },


            str2abnew: function(str) {
                var typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
                    return parseInt(h, 16)
                }))
                var buffer = typedArray.buffer;
                return buffer;
            },

            // ArrayBuffer转16进度字符串示例
            ab2hex(buffer) {
                var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (
                    bit
                ) {
                    return ("00" + bit.toString(16)).slice(-2);
                });
                return hexArr.join("");
            },

            // 切换tab
            switchTab(code) {
                console.log(code);

                //this.activeTab = code;
            }
        }
    };
</script>

<style lang="wxss">
  page {
    width: 100%;
    height: 100%;
    background-color: #f7fbff;
  }
</style>

<style scoped>
  /* 头部菜单 */
  .nav-bar {
    width: 100%;
    height: 1rem;
    background: #fff;
    box-shadow: 0px 2px 4px 0px rgba(7, 127, 255, 0.1);
  }

  .nav-bar .nav-item {
    display: inline-block;
    width: 100%;
    height: 1rem;
    line-height: 1rem;
    text-align: center;
  }

  .nav-bar .nav-item .item-word {
    display: inline-block;
    box-sizing: border-box;
    padding: 0 5px;
    font-size: 0.28rem;
    color: #767d8f;
    height: 1rem;
    width:100%;
  }

  .nav-bar .nav-item .item-word.active {
    color: #0077ff;
    border-bottom: 2px solid #0077ff;
  }

  .item-list {
    box-shadow: 0px 2px 4px 0px rgba(7, 127, 255, 0.1);
    margin-top: 10px;
    padding-left: 10px;
    padding-right: 10px;
    background-color: #ffffff;
  }

  .item {
    height: 40px;
    font-size: 15px;
    font-family: PingFang SC;
    font-weight: 500;
    background-color: #ffffff;
    line-height: 40px;
    padding-left: 8px;
    border-bottom: 1px solid #e8eaf0;
  }

  .item span {
    color: #373e4f;
  }

  .item .yitianjia {
    height: 30px;
    float: right;
    font-size: 12px;
    font-family: PingFang SC;
    font-weight: 500;
    margin-right: 8px;
  }

  .item a {
    height: 30px;
    float: right;
    font-size: 12px;
    font-family: PingFang SC;
    font-weight: 500;
    color: rgba(0, 119, 255, 1);
    margin-right: 8px;
  }

  p {
    font-size: 12px;
    font-family: PingFang SC;
    font-weight: 500;
    color: rgba(118, 125, 143, 1);
    line-height: 15px;
  }

  .no-data {
    color: #a3aab7;
    width: 2rem;
    height: 0.3rem;
    margin: 0 auto;
    margin-top: 0.3rem;
    text-align: center;
    font-size: 0.24rem;
    line-height: 0.26rem;
  }

  .foot {
    text-align: center;
    vertical-align: middle;
    width: 100%;
    height: 40px;
    position: fixed;
    bottom: 0;
    background-color: #0077ff;
    font-size: 15px;
    font-family: PingFang SC;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
    line-height: 40px;
  }
</style>
